﻿using System;
using System.Collections.Generic;
using System.Linq;
using Ext.Net;
using WEB.Core.Controls;
using WEB.BLL.Entities;
using WEB.BLL.Services;
using WEB.BLL;
using WEB.Core.Util;

namespace WEB.APP
{
    public partial class _Default : BasePage
    {
        public _Default()
            : base(SCREENS.MAIN,false,false,false)
        {

        }
        protected override void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender,e);
            BinModule();
            if (!IsPostBack && !X.IsAjaxRequest)
            {
                statusMain.DefaultText += HostName;
            }
        }

        [DirectMethod]
        public void DocumentReady()
        {
            try
            {
                BinScreenData();
                sButtonUser.Text = CurrentUser.UserName;
                BinTreeFromDesktop();
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }

        [DirectMethod]
        public void LoadScreen(string moduleId, string moduleName)
        {
            // Ext.Net.Button btn = (Ext.Net.Button)sender;
            BinTreeFunction(moduleId, moduleName);
            pnlNavigator.Title = moduleName.ToUpper();
        }

        private void BinScreenData()
        {
            try
            {
                ScreenService screenService = ScreenService.GetInstance();
                IList<ScreenEntity> lstScreen = screenService.LoadAll();
                for (int i = 0; i < lstScreen.Count; i++)
                {
                    lstScreen[i].HostName = this.HostName;
                }
                stScreen.DataSource = lstScreen;
                stScreen.DataBind();
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }
        private void BinModule()
        {
            try
            {
                if (WEBContext.Current.User == null || WEBContext.Current.User.RoleId <= 0) return;

                ModuleEntity moduleE = new ModuleEntity();
                moduleE.RoleId = WEBContext.Current.User.RoleId;

                ModuleService moduleService = ModuleService.GetInstance();
                IList<ModuleEntity> lstModule = moduleService.LoadModuleHasChild(moduleE);
                if (lstModule == null) return;
                foreach (ModuleEntity module in lstModule)
                {
                    Ext.Net.SplitButton button = new Ext.Net.SplitButton();
                    button.Text = module.ModuleName;
                    button.ID = "btn" + module.ModuleId;
                    button.StateID = module.ModuleId;
                    button.IconCls = module.ModuleId.ToLower();

                    //add menu item
                    Ext.Net.Menu menu = new Ext.Net.Menu();
                    ScreenEntity screenE = new ScreenEntity();
                    screenE.RoleId = WEBContext.Current.User.RoleId;
                    screenE.Module = module.ModuleId;
                    ScreenService screenService = ScreenService.GetInstance();
                    IList<ScreenEntity> screens = screenService.LoadScreenByModuleAndRole(screenE);
                    foreach (ScreenEntity screen in screens)
                    {
                        if (screen.ScreenId == SCREENS.REPORTPROJECTDETAIL)
                            continue;
                        Ext.Net.MenuItem menuItem = new Ext.Net.MenuItem();
                        if (screen.IsUse) continue;
                        if (!string.IsNullOrEmpty(screen.Parent))
                        {
                            //add menu item cho menu parent
                            List<ScreenEntity> screensChild = GetScreenByParentId(screens, screen.Parent);
                            Ext.Net.Menu menuChild = new Ext.Net.Menu();
                            Ext.Net.MenuItem menuItemChild = new Ext.Net.MenuItem();
                            foreach (ScreenEntity screenChild in screensChild)
                            {
                                if (screenChild.ScreenId == SCREENS.REPORTPROJECTDETAIL)
                                    continue;
                                menuItemChild = new Ext.Net.MenuItem(screenChild.ScreenName);
                                menuItemChild.Text = screenChild.ScreenName;
                                menuItemChild.ID = "mi" + screenChild.ScreenId;
                                menuItemChild.Icon = GetIcon(screenChild.Icon);
                                menuItemChild.Listeners.Click.Fn = "LoadTab";
                                menuChild.Items.Add(menuItemChild);
                                screenChild.IsUse = true;
                            }
                            //add menu parent
                            menuItem = new Ext.Net.MenuItem(screen.Parent);
                            menuItem.Text = screen.Parent;
                            menuItem.Icon = Icon.Folder;
                            menuItem.Menu.Add(menuChild);
                            menu.Items.Add(menuItem);
                        }
                        else
                        {
                            //add menu cung cap voi menu parent
                            menuItem.Text = screen.ScreenName;
                            menuItem.ID = "mi" + screen.ScreenId;
                            menuItem.Icon = GetIcon(screen.Icon);
                            menuItem.Listeners.Click.Fn = "LoadTab";
                            menu.Items.Add(menuItem);
                            screen.IsUse = true;
                        }
                    }
                    menu.IgnoreParentClicks = true;
                    button.Menu.Add(menu);
                    if (screens.Count <= 0)
                        continue;

                    //button.DirectClick += new ComponentDirectEvent.DirectEventHandler(button_DirectClick);
                    button.Listeners.Click.Fn = "LoadScreen";
                    button.Scale = ButtonScale.Medium;
                    button.IconAlign = IconAlign.Left;

                    tbModule.Items.Add(button);
                    tbModule.Items.Add(new ToolbarSeparator());
                }
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }
        protected void btnList_Click(object sender, DirectEventArgs e)
        {


        }

        private void BinTreeFunction(string moduleId, string moduleName)
        {
            try
            {
                if (WEBContext.Current.User == null || WEBContext.Current.User.RoleId <= 0) return;
                //Ext.Net.TreeNode root = new Ext.Net.TreeNode(moduleName);
                Ext.Net.TreeNodeCollection nodes = new Ext.Net.TreeNodeCollection();

                ScreenEntity screenE = new ScreenEntity();
                screenE.RoleId = WEBContext.Current.User.RoleId;
                screenE.Module = moduleId;

                ScreenService screenService = ScreenService.GetInstance();
                IList<ScreenEntity> screens = screenService.LoadScreenByModuleAndRole(screenE);

                if (screens.Count <= 0)
                {
                    ResourceManager.RegisterOnReadyScript("treeNavigator.root.setText('Desktop');");
                    return;
                }
                //List<ScreenEntity> screensRoot = GetScreenByParentId(screens, moduleId);
                foreach (ScreenEntity screen in screens)
                {
                    if (screen.ScreenId == SCREENS.REPORTPROJECTDETAIL)
                        continue;
                    Ext.Net.TreeNode screenNode = new Ext.Net.TreeNode();
                    if (screen.IsUse) continue;
                    if (!string.IsNullOrEmpty(screen.Parent))
                    {
                        screenNode = new Ext.Net.TreeNode(screen.Parent, Icon.Folder);
                        screenNode.Leaf = false;
                        screenNode.NodeID = screen.Parent;
                        screenNode.Text = screen.Parent;
                        screenNode.Expanded = true;
                        screenNode.Expandable = ThreeStateBool.True;

                        treeNavigator.AppendChild("root", screenNode);
                        //screen.IsUse = true;

                        List<ScreenEntity> screensChild = GetScreenByParentId(screens, screen.Parent);
                        foreach (ScreenEntity screenChild in screensChild)
                        {
                            if (screenChild.ScreenId == SCREENS.REPORTPROJECTDETAIL)
                                continue;
                            Ext.Net.TreeNode screenNodeChild = new Ext.Net.TreeNode(screenChild.ScreenName, GetIcon(screenChild.Icon));
                            screenNodeChild.Leaf = false;
                            screenNodeChild.NodeID = screenChild.ScreenId;
                            screenNodeChild.Text = screenChild.ScreenName;
                            screenNodeChild.Icon = GetIcon(screenChild.Icon);
                            treeNavigator.AppendChild(screenNode.NodeID, screenNodeChild);
                            screenChild.IsUse = true;
                        }
                    }
                    else
                    {
                        screenNode.Leaf = true;
                        screenNode.NodeID = screen.ScreenId;
                        screenNode.Text = screen.ScreenName;
                        screenNode.Icon = GetIcon(screen.Icon);
                        screenNode.Expanded = true;
                        treeNavigator.AppendChild("root", screenNode);
                        screen.IsUse = true;
                    }

                    //List<ScreenEntity> screensChild = GetScreenByParentId(screens, screen.ScreenId);
                    //foreach (ScreenEntity screenChild in screensChild)
                    //{
                    //    Ext.Net.TreeNode screenNodeChild = new Ext.Net.TreeNode(screenChild.ScreenName, GetIcon(screenChild.Icon));
                    //    screenNodeChild.Leaf = false;
                    //    //screenNodeChild.NodeID = string.Format("{0}/Modules/{1}/{2}.{3}?id={4}", this.HostName, screenChild.Module, screenChild.FileName, screenChild.Extention, screenChild.ScreenId);
                    //    screenNodeChild.NodeID = screenChild.ScreenId;
                    //    screenNodeChild.Text = screenChild.ScreenName;
                    //    treeNavigator.AppendChild(screenNode.NodeID, screenNodeChild);
                    //}
                }
            }
            catch (Exception ex)
            {
                Notification(ex);
            }

        }

        [DirectMethod]
        public void LoadTreeFromDesktop()
        {
            Ext.Net.TreeNodeCollection nodes = new Ext.Net.TreeNodeCollection();
            ScreenEntity screenE = new ScreenEntity();
            screenE.UserName = WEBContext.Current.User.UserName;
            ScreenService screenService = ScreenService.GetInstance();
            IList<ScreenEntity> screens = screenService.LoadScreenByDesktop(screenE);
            if (screens == null) return;
            string _flagModule = "";
            string _flagParent = "";
            foreach (ScreenEntity screen in screens)
            {
                Ext.Net.TreeNode screenNode = new Ext.Net.TreeNode(screen.ScreenName, GetIcon(screen.Icon));
                screenNode.Leaf = true;
                screenNode.NodeID = screen.ScreenId;
                screenNode.Text = screen.ScreenName;
                screenNode.Expanded = true;

                if (_flagModule.IndexOf(",md" + screen.Module) < 0)
                {
                    Ext.Net.TreeNode _tnModule = new Ext.Net.TreeNode("md" + screen.Module, Icon.Folder);
                    _tnModule.Leaf = false;
                    _tnModule.NodeID = "md" + screen.Module;
                    _tnModule.Text = screen.ModuleName;
                    _tnModule.Expanded = true;
                    _tnModule.Expandable = ThreeStateBool.True;
                    treeNavigator.AppendChild("root", _tnModule);

                    _flagModule += ",md" + screen.Module;
                }
                if (!string.IsNullOrEmpty(screen.Parent))
                {
                    if (_flagParent.IndexOf(",pt" + screen.Parent) < 0)
                    {
                        Ext.Net.TreeNode _tnParent = new Ext.Net.TreeNode("pt" + screen.Parent, Icon.Folder);
                        _tnParent.Leaf = false;
                        _tnParent.NodeID = "pt" + screen.Parent;
                        _tnParent.Text = screen.Parent;
                        _tnParent.Expanded = true;
                        _tnParent.Expandable = ThreeStateBool.True;
                        treeNavigator.AppendChild("md" + screen.Module, _tnParent);

                        _flagParent += ",pt" + screen.Parent;
                    }
                    treeNavigator.AppendChild("pt" + screen.Parent, screenNode);
                }
                else
                {
                    treeNavigator.AppendChild("md" + screen.Module, screenNode);
                }
            }
            pnlNavigator.Title = "BÀN LÀM VIỆC";
        }
        /// <summary>
        /// Lấy danh sách màn hình từ thiết lập form bàn làm việc
        /// </summary>
        private void BinTreeFromDesktop()
        {
            try
            {
                Ext.Net.TreeNodeCollection nodes = new Ext.Net.TreeNodeCollection();
                ScreenEntity screenE = new ScreenEntity();
                screenE.UserName = WEBContext.Current.User.UserName;
                ScreenService screenService = ScreenService.GetInstance();
                IList<ScreenEntity> screens = screenService.LoadScreenByDesktop(screenE);

                if (screens.Count <= 0)
                    LoadScreen("List", "List");
                string _flagModule = "";
                string _flagParent = "";
                foreach (ScreenEntity screen in screens)
                {
                    Ext.Net.TreeNode screenNode = new Ext.Net.TreeNode(screen.ScreenName, GetIcon(screen.Icon));
                    screenNode.Leaf = true;
                    screenNode.NodeID = screen.ScreenId;
                    screenNode.Text = screen.ScreenName;
                    screenNode.Expanded = true;

                    if (_flagModule.IndexOf(",md" + screen.Module) < 0)
                    {
                        Ext.Net.TreeNode _tnModule = new Ext.Net.TreeNode("md" + screen.Module, Icon.Box);
                        _tnModule.Leaf = false;
                        _tnModule.NodeID = "md" + screen.Module;
                        _tnModule.Text = screen.ModuleName;
                        _tnModule.Expanded = true;
                        _tnModule.Expandable = ThreeStateBool.True;
                        treeNavigator.AppendChild("root", _tnModule);

                        _flagModule += ",md" + screen.Module;
                    }
                    if (!string.IsNullOrEmpty(screen.Parent))
                    {
                        if (_flagParent.IndexOf(",pt" + screen.Parent) < 0)
                        {
                            Ext.Net.TreeNode _tnParent = new Ext.Net.TreeNode("pt" + screen.Parent, Icon.Folder);
                            _tnParent.Leaf = false;
                            _tnParent.NodeID = "pt" + screen.Parent;
                            _tnParent.Text = screen.Parent;
                            _tnParent.Expanded = true;
                            _tnParent.Expandable = ThreeStateBool.True;
                            treeNavigator.AppendChild("md" + screen.Module, _tnParent);

                            _flagParent += ",pt" + screen.Parent;
                        }
                        treeNavigator.AppendChild("pt" + screen.Parent, screenNode);
                    }
                    else
                    {
                        treeNavigator.AppendChild("md" + screen.Module, screenNode);
                    }
                    pnlNavigator.Title = "Desktop";
                }
            }

            catch (Exception ex)
            {
                Notification(ex);
            }

        }
        //private void BinChildFunction(IList<ScreenEntity> screens, string parent, Ext.Net.TreeNode parentNode)
        //{
        //    foreach (ScreenEntity screen in screens)
        //    {
        //        if (screen.Parent != null && screen.Parent.Equals(parent))
        //        {
        //            Ext.Net.TreeNode screenNode = new Ext.Net.TreeNode(screen.ScreenName, GetIcon(screen.Icon));
        //            screenNode.Leaf = true;
        //            //screenNode.NodeID = string.Format("{0}/Modules/{1}/{2}.{3}", this.HostName, screen.Module, screen.FileName, screen.Extention);
        //            screenNode.NodeID = screen.ScreenId;
        //            screenNode.Text = screen.ScreenName;
        //            parentNode.Nodes.Add(screenNode);
        //            screens.Remove(screen);
        //        }
        //    }
        //}
        private Icon GetIcon(string iconName)
        {
            Type mytype = typeof(Icon);
            foreach (Icon icon in Enum.GetValues(mytype))
            {
                if (icon.ToString() == iconName)
                {
                    return icon;
                }
            }
            return Icon.Application;
        }

        private List<ScreenEntity> GetScreenByParentId(IList<ScreenEntity> screens, string ParentId)
        {
            try
            {
                List<ScreenEntity> newListScreen = new List<ScreenEntity>();


                foreach (ScreenEntity screen in screens)
                {
                    if (!screen.IsUse && !string.IsNullOrEmpty(screen.Parent) && screen.Parent.Equals(ParentId))
                    {
                        newListScreen.Add(screen);

                    }

                }

                return newListScreen;
            }
            catch (Exception ex)
            {
                Notification(ex);
                return null;
            }
        }
        protected void btnWareHouse_Click(object sender, DirectEventArgs e)
        {
        }

        /// <summary>
        /// Màn hình thay đổi password
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        #region ChangePass
        ///Lưu pass
        protected void btnChange_Click(object sender, DirectEventArgs e)
        {
            try
            {
                UserEntity userE = new UserEntity();
                UserService userS = UserService.GetInstance();
                userE.UserName = WEBContext.Current.User.UserName;
                userE = userS.LoadByPrimaryKey(userE);
                if (userE != null)
                {
                    if (userE.Password.ToLower() == Encryption.StringToMD5Hash(txtOldPassword.Text).ToLower())
                    {
                        userE.UserName = txtUserName.Text;
                        userE.Password = Encryption.StringToMD5Hash(txtPassword.Text);
                        if (CurrentUser.RoleId == 2)
                            ClientService.GetInstance().UpdatePassword(new ClientEntity() { Username = userE.UserName, Password = userE.Password });
                        else
                            userS.UpdatePassword(userE);
                        lblError.Text = "Change the password successfully";
                        txtOldPassword.Reset();
                        txtPassword.Reset();
                        txtConfirmPassword.Reset();
                        lblError.Icon = Icon.Accept;
                        lblError.Show();
                    }
                    else
                    {
                        lblError.Text = "The passwords current action is not valid";
                        lblError.Icon = Icon.Exclamation;
                        lblError.Show();
                    }
                }
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }
        //Load form thay đổi pass
        protected void menuChange_Click(object sender, DirectEventArgs e)
        {
            FormChangePass.Reset();
            lblError.Hidden = true;
            txtUserName.Text = WEBContext.Current.User.UserName;
            winChangePass.Show();
        }
        #endregion

        #region
        [DirectMethod]
        public void checkStatus(string ScreenId)
        {
            DesktopEntity desktopE = new DesktopEntity();
            DesktopService desktopS = DesktopService.GetInstance();
            desktopE.UserName = WEBContext.Current.User.UserName;
            desktopE.ScreenId = ScreenId;
            desktopE = desktopS.LoadByPrimaryScreen(desktopE);

        }

        [DirectMethod]
        public void favScreen(string ScreenId)
        {
            try
            {
                DesktopEntity desktopE = new DesktopEntity();
                DesktopService desktopS = DesktopService.GetInstance();
                desktopE.UserName = WEBContext.Current.User.UserName;
                desktopE.ScreenId = ScreenId;
                desktopE = desktopS.LoadByPrimaryScreen(desktopE);
                if (desktopE != null)
                {
                    desktopS.Delete(desktopE);
                    //X.Msg.Alert("Notice", "Detele completed").Show();
                }
                else
                {
                    desktopE = new DesktopEntity();
                    desktopE.UserName = WEBContext.Current.User.UserName;
                    desktopE.ScreenId = ScreenId;
                    desktopE.CreatedDate = DateTime.Now;
                    desktopE.UpdatedDate = DateTime.Now;
                    desktopS.Insert(desktopE);
                    //X.Msg.Alert("Notice", "Save Complete").Show();
                }
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }
        #endregion

    }

}
